<template>
  <div class="container">
    <!-- <el-row>
      <el-col class="topTitle">
        <i class="icon iconfont iconfanhui1" @click="goBack"></i>
          <span class="el-dropdown-link titleStyle">
            {{projectName}}
          </span>
          <span class="status">已开工</span>
      </el-col>
    </el-row> -->

    <topTitle
      :titleText="projectName"
      :back="back"
      @gobackTriser="goBack"
      status="已开工"
    ></topTitle>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="164px"
        class="demo-formData"
      >
        <el-row>
          <el-form-item label="受理机构：" class="row-padding-bottom">
            {{ formData.bureau }}
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item
            prop="insNo"
            label="单位编号："
            class="row-padding-bottom"
          >
            <el-input
              class="sWidth"
              v-model="formData.insNo"
              placeholder="请输入单位编号"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            prop="insDate"
            label="参保时间："
            class="row-padding-bottom"
          >
            <el-date-picker
              class="sWidth"
              v-model="formData.insDate"
              type="date"
              placeholder="选择日期"
              clearable
              :style="{ width: '100%' }"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item
            prop="companyIndex"
            label="参保单位："
            class="row-padding-bottom"
          >
            <el-select
              class="mWidth"
              v-model="companyIndex"
              filterable
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="(item, index) in companyList"
                :key="item.id"
                :label="item.companyName"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            prop="insurancedName"
            label="参保人员："
            class="row-padding-bottom"
          >
            <div class="uploadBox">
              <span class="peopleNum">{{ formData.total }}</span>
              <!-- <el-button round class="uploadImg" @click="showEmployeeList">修改</el-button> -->
              <el-link type="primary" @click="showEmployeeList">修改</el-link>
            </div>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              prop="upLoadFile"
              :label="isCzUser() ? '完税证明：' : '参保凭证：'"
              v-model="formData.fileList"
            >
              <uploadAnnex
                @getFileList="getFileListInsurance"
                :limitationFactor="limitationFactorInsurance"
                @getFile="getFileInsurance"
                :upLoadFile="upLoadFile"
              />
              <div class="tips" v-if="isHsUser()">
                请上传工伤保险参保登记表（<el-link
                  type="primary"
                  @click="typicalDrawing('1')"
                  >查看示例图</el-link
                >)、税收完税证明（<el-link
                  type="primary"
                  @click="typicalDrawing('2')"
                  >查看示例图</el-link
                >)或社会保险单位基本情况表（<el-link
                  type="primary"
                  @click="typicalDrawing('3')"
                  >查看示例图</el-link
                >)作为参保凭证附件格式支持png，jpg，jpeg，
                doc，docx，xls，xlsx，pdf，最多上传10个附件
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <uploadResult
              :resultList="upLoadFile"
              @callBackResult="getFileInsurance"
            />
          </el-col>
        </el-row>
        <el-form-item class="submitBox">
          <el-button
            type="primary"
            class="commonBut saveBtn"
            :loading="isSaveLoading"
            @click="saveForm"
            >保存</el-button
          >
          <el-button class="commonBut" @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
      <!-- 图片预览 -->
      <el-image
        class="previewImg"
        style="width: 56px; height: 0px"
        src="../../../static/img/monitorHome/card.png"
        :preview-src-list="typicalDrawingSrcList"
        id="seeExampleBox"
      ></el-image>
    </div>

    <el-dialog
      title="修改参保人员"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      @close="cancelAdd"
      width="900px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-transfer
        filterable
        :filter-method="filterMethod"
        :titles="['参保人员', '已选择的人员']"
        class="insuranceTransfer"
        filter-placeholder="请输入姓名或身份证号码"
        v-model="insurancedName"
        :data="insuranceData"
      >
      </el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd" class="cancel">取 消</el-button>
        <el-button type="primary" class="save" @click="addInsured"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import common from '../../kits/common'

export default {
  name: 'editInsurance',
  components: {},
  data() {
    const generateData = (_) => {
      const data = []
      const users = [
        { name: '张三', cardId: '254****253', id: 0 },
        { name: '李四', cardId: '254****254', id: 1 },
        { name: '王五', cardId: '254****255', id: 2 },
        { name: '李欣', cardId: '254****256', id: 3 },
      ]
      users.forEach((item) => {
        data.push({
          label: item.name + '  ' + item.cardId,
          key: item.id,
        })
      })
      return data
    }
    var checkCompanyIndex = (rule, value, callback) => {
      var that = this
      if (that.companyIndex.length == 0) {
        return callback(new Error('参保单位不能为空'))
      } else {
        callback()
      }
    }
    var checkInsurancedName = (rule, value, callback) => {
      var that = this
      if (this.isCzUser()) {
        callback()
        return
      }
      if (that.insurancedName.length == 0) {
        return callback(new Error('参保人员不能为空'))
      } else {
        callback()
      }
    }
    var checkUpLoadFile = (rule, value, callback) => {
      var that = this
      if (that.upLoadFile.length == 0) {
        return callback(
          new Error(that.isCzUser() ? '完税证明不能为空' : '参保凭证不能为空')
        )
      } else {
        callback()
      }
    }

    return {
      insuranceData: [], //generateData(),
      insurancedName: [],
      filterMethod(query, item) {
        return item.label.indexOf(query) > -1
      },
      insId: '',
      projectId: '',
      projectName: '',
      companyList: [],

      company: {},
      dialogFormVisible: false,

      tableList: [],
      currentPage: 1,
      pageSize: 30,
      currentTotal: 0,

      isShow: false, //列表加载
      // loading: true, //列表loading
      canLogin: false, //保存loading

      upLoadFile: [],
      oldSrcList: [],
      dialogImageUrl: '',
      srcList: [],
      isSaveLoading: false, // 保存loading
      companyIndex: '',
      formData: {
        insNo: '', //保险单号  -----必传
        insDate: '', //参保日期  -----必传
        projectId: '', //项目id  -----必传
        companyName: '', //参保企业名（不包含括号内） -----必传
        companyType: '', //参保企业类型 01 05 10  -----必传
        uscc: '', //参保企业uscc  -----必传
        bureau: '', //受理机构  -----必传
        batchNo: '1', //批次号  -----必传
        fileList: [], //文件对象数组  -----非必传
        employeeList: [],
        total: 0,
      },

      filterField: {
        searchText: '',
      },
      formRules: {
        insNo: [
          {
            required: true,
            message: '单位编号不能为空',
            trigger: 'blur',
          },
        ],
        insDate: [
          {
            required: true,
            message: '参保时间不能为空',
            trigger: 'blur',
          },
        ],
        companyIndex: [
          { required: true, validator: checkCompanyIndex, trigger: 'change' },
        ],
        insurancedName: [
          {
            required: true,
            validator: checkInsurancedName,
            trigger: 'blur',
          },
        ],
        upLoadFile: [
          {
            required: true,
            validator: checkUpLoadFile,
            trigger: 'blur',
          },
        ],
      },
      insuredPersonnel: [], //添加参保人员点击确定保存数据
      insuredPersonnelList: [],
      // 保单
      limitationFactorInsurance: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        fileId: 'salaryExcelInsurance', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelInsuranceForm', //自定义id解决一个页面包含多个上传附件

        messagetip:
          '要求格式为png，jpg，jpeg，doc，docx，xls，xlsx，pdf格式，附件大小不超过5M', //自定义报错提示语
        // methodTip:"请上传保单回执，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件", //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      back: true,
    }
  },
  activated: function () {},
  created() {
    this.insId = this.$route.query.insId
    this.projectId = this.$route.query.projectId
    this.projectName = this.$route.query.projectName
    this.getCompanyListData()
    //滁州参保人员为非必填
    if (this.isCzUser()) {
      this.formRules.insurancedName[0].required = false
      this.limitationFactorInsurance.methodTip =
        '请上传完税证明，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件'
    }
    if (this.isHsUser()) {
      this.formRules.insurancedName[0].required = true
      this.limitationFactorInsurance.methodTip = ''
    } else {
      this.formRules.insurancedName[0].required = true
      this.limitationFactorInsurance.methodTip =
        '请上传保单回执，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件'
    }
  },
  methods: {
    getDetail() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/ins/expand/info',
        data: { insId: this.insId },
      })
        .then((response) => {
          var data_info = response.data.result
          this.formData.id = data_info.id //保险单号  -----必传
          this.formData.insNo = data_info.insNo //保险单号  -----必传
          this.formData.insDate = data_info.insDate //参保日期  -----必传
          this.formData.projectId = data_info.projectId //项目id  -----必传
          this.formData.companyName = data_info.companyName //参保企业名（不包含括号内） -----必传

          this.formData.companyType = data_info.companyType //参保企业类型 01 05 10  -----必传
          this.formData.uscc = data_info.uscc //参保企业uscc  -----必传
          this.formData.total = data_info.total

          for (let i = 0; i < this.companyList.length; i++) {
            if (
              this.companyList[i].companyName == this.formData.companyName &&
              this.companyList[i].uscc == this.formData.uscc
            ) {
              this.companyIndex = i
              break
            }
          }

          this.formData.bureau = data_info.bureau //受理机构  -----必传
          this.formData.batchNo = data_info.batchNo //批次号  -----必传

          this.upLoadFile = data_info.fileList || []
          for (var i = 0; i < this.upLoadFile.length; i++) {
            this.srcList.push(this.upLoadFile[i].url)
            this.oldSrcList.push(this.upLoadFile[i].url)
          }

          this.formData.employeeList = data_info.employeeList
          this.searchList() //初始选中的人
          //this.infos);
        })
        .catch((error) => {})
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    /**
     * @description: 改变图片地址
     */
    changeSrcList(val) {
      this.srcList = val
    },
    getCompanyListData() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/insdetail/expand/projectInfo',
        data: { projectId: this.projectId },
      })
        .then((resp) => {
          if (!resp.data.hasError) {
            this.companyList = resp.data.result.companyList
            this.formData.bureau = resp.data.result.bureau //参保企业uscc  -----必传
          } else {
            this.$message({
              showClose: true,
              duration: 3000,
              message: resp.data.errorMsg,
              type: 'error',
            })
          }
          this.getDetail()
        })
        .catch((resp) => {
          this.$message.error('数据获取失败')
        })
    },
    saveForm() {
      this.$refs.formData.validate((valid) => {
        this.formData.fileList = JSON.stringify(this.upLoadFile) //this.upLoadFile;
        var employeeTempList = []
        this.insurancedName.forEach((item) => {
          employeeTempList.push(this.insuranceData[item]['item'].contractId)
        })
        if (this.isCzUser() && employeeTempList.length < 1) {
          employeeTempList = [0]
        }

        this.formData.employeeList = JSON.stringify(employeeTempList)

        this.formData.projectId = this.projectId //项目id  -----必传
        this.formData.companyName =
          this.companyList[this.companyIndex].companyName //参保企业名（不包含括号内） -----必传
        this.formData.companyType = this.companyList[this.companyIndex].type //参保企业类型 01 05 10  -----必传
        this.formData.uscc = this.companyList[this.companyIndex].uscc //参保企业uscc  -----必传

        if (valid) {
          this.isSaveLoading = true
          this.saveFormInfo()
        } else {
          return false
        }
      })
    },
    saveFormInfo() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/ins/expand/editins',
        data: this.formData,
      })
        .then((response) => {
          this.isSaveLoading = false

          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '保存成功',
            })
            this.formVisible = false
            this.goBack()
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg,
            })
          }
        })
        .catch((error) => {
          // this.$message.error("数据获取失败");
          //this.$message.error("保存失败");
          this.isSaveLoading = false
        })
    },

    goBack() {
      if (this.$route.query.fromPath) {
        this.$router.push({
          path: '/home/insurance/insuranceDetail',
          name: 'insuranceDetail',
          query: {
            insId: this.insId,
            id: this.$route.query.id,
            projectName: this.projectName,
            projectStatus: this.$route.query.projectStatus,
            projectStatusDesc: this.$route.query.projectStatusDesc,
            projectId: this.projectId,
          },
        })
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/insurance/insuranceList',
          newUrl: this.$router.currentRoute.fullPath,
        })
      } else {
        this.$router.push({
          path: '/home/insurance/insurance',
          name: 'insurance',
          query: {
            projectId: this.projectId,
            projectName: this.projectName,
          },
        })
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/insurance/insurance',
          newUrl: this.$router.currentRoute.fullPath,
        })
      }
    },
    showEmployeeList(id) {
      this.filterField.insId = id
      this.searchList()
      this.dialogFormVisible = true
    },

    searchList() {
      this.insuranceData = []
      this.insurancedName = []
      //generateData(),
      this.axios({
        method: 'POST',
        url: 'api-e/cs/insdetail/expand/employeelist',
        data: {
          searchText: this.filterField.searchText,
          projectId: this.projectId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.insuredPersonnelList = response.data.result
            this.insuredPersonnelList.forEach((item, index) => {
              this.insuranceData.push({
                label: item.name + '  ' + item.idcard,
                key: index,
                item: item,
              })
            })
            //选中已有胡人员
            if (this.insuredPersonnel.length != 0) {
              this.insurancedName = this.insuredPersonnel
            } else {
              if (this.formData.employeeList == '[]') {
                this.insurancedName = []
                return
              }
              this.formData.employeeList.forEach((item2, index2) => {
                this.insuredPersonnelList.forEach((item, index) => {
                  if (item2.employeeId == item.employeeId) {
                    this.insurancedName.push(index)
                  }
                })
              })
            }
          }
        })
        .catch((error) => {
          this.$message.error('数据获取失败')
        })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.searchList()
    },
    handleCurrentChange(val) {
      this.currentPage = val

      this.searchList()
    },
    cancelAdd() {
      this.dialogFormVisible = false
      if (this.insuredPersonnel.length != 0) {
        this.insurancedName = this.insuredPersonnel
      } else {
        this.searchList()
      }
    },
    addInsured() {
      this.insuredPersonnel = this.insurancedName
      this.dialogFormVisible = false
      //保存参保人数变化
      this.formData.total = this.insuredPersonnel.length
    },
    getFileListInsurance(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    getFileInsurance(val) {
      this.upLoadFile = val
    },
    // 查看示例
    typicalDrawing(index) {
      var url = common.uploadUrl + '/statics/template/INS' + index + '.png'
      this.typicalDrawingSrcList = [url]
      $('#seeExampleBox').click()
    },
  },
}
</script>
<style scoped lang="less">
.insuranceTransfer {
  /deep/ .el-transfer-panel {
    // width: 220px;
    width: calc((100% - 122px) / 2);
  }
  /deep/ .el-transfer__button {
    display: block;
    margin: 10px 0 0 0 !important;
    padding: 8px 20px;
  }
  /deep/ .el-icon-arrow-left,
  /deep/ .el-icon-arrow-right {
    font-size: 20px;
  }
}
.topTitle {
  height: 67px;
  background-color: #e4ebf1;
  padding-left: 24px;
  font: bold 18px/67px Microsoft YaHei;
  .titleStyle {
    color: #333;
    font-size: 18px;
    .el-icon-caret-bottom {
      color: #71818e;
    }
  }
  .status {
    display: inline-block;
    width: 60px;
    height: 20px;
    line-height: 20px;
    margin-bottom: 10px;
    background: #009588;
    color: #fff;
    text-align: center;
    font-size: 12px;
    border-radius: 4px;
  }
  .saveBtn {
    margin-right: 24px;
    margin-top: 15.5px;
  }
}

.container {
  .mainCon {
    height: calc(100% - 50px);
    padding: 40px 10px;
    overflow-y: auto;
    .labelStyMin {
      padding-left: 0px !important;
      min-width: 130px;
    }
    .labelStyMax {
      padding-left: 0px !important;
      margin-left: 5px;
      min-width: 155px;
    }
    .submitBox {
      text-align: left;
      margin-top: 10px;
    }
    .picStyle {
      width: 116px;
      margin-right: 60px;
      img {
        width: 100%;
      }
    }
    .uploadBox {
      position: relative;
      .peopleNum {
        color: #666;
        margin-right: 20px;
      }
      /deep/ .el-link.el-link--primary {
        line-height: 25px;
        margin-top: -4px;
      }
      .uploadImg {
        width: 96px;
        height: 36px;
        color: #009588;
        border: 1px solid #009588;
        line-height: 10px;
      }
      .uploadImgState {
        font-size: 14px;
        color: #999999;
        margin-left: 12px;
      }
      .upLoadDom {
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        input {
          width: 100px;
          height: 36px;
        }
      }
    }
    .imgStyle {
      padding-left: 130px;
      li {
        position: relative;
        margin-right: 20px;
        margin-top: 10px;
        i {
          position: absolute;
          right: -6px;
          top: -10px;
          font-size: 20px;
        }
      }
    }
  }
}
form.el-form.demo-formData {
  /*width: 450px;*/
  display: inline-block;
  text-align: left;
  // .el-input,
  // .el-select{
  //   width: 320px !important;
  // }
  // .selectWidth {
  //   width: 100%;
  // }
}
//   .el-main .el-form-item {
//     margin-bottom: 20px;
//   }
.saveBtn {
  background-color: #009588;
  border-color: #009588;
  color: #fff;
}

.tips {
  color: #999;
  line-height: 20px;
  // padding: 6px 0 8px;
  a {
    color: #265faa;
  }
}
</style>
